package com.ls.lserp.modules.produce.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.map.HashedMap;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.support.RequestContext;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.DateUtils;
import com.ls.lserp.common.utils.excel.ExportExcel;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.produce.entity.ProduceWorkticketEntity;
import com.ls.lserp.modules.produce.entity.WorkticketEntity;
import com.ls.lserp.modules.produce.service.ProduceWorkticketService;

import freemarker.template.Configuration;

@Controller
@RequestMapping(value = "${adminPath}/produce/workticket/")
public class ProduceWorkticketController extends BaseController {
	
    @Autowired
    private ProduceWorkticketService produceWorkticketService;
    
    private SXSSFWorkbook sky = new SXSSFWorkbook ();
    
    @Autowired
    Configuration freemarkerConfiguration;


    /**
     * 生产工票一览画面
     *
     * @return
     */
    @RequestMapping(value = {""})
    public String produceWorkticket(Model model) {
        //获取班组名称
        List<ProduceWorkticketEntity> groupList = produceWorkticketService.getGroupList();
        // 前台select组件使用（班组名称）
        model.addAttribute ("groupList", groupList);
        
        //获取工序信息
        List<ProduceWorkticketEntity> operatingList = produceWorkticketService.getOperatingList();
        // 前台select组件使用（工序信息）
        model.addAttribute ("operatingList", operatingList);

        return "modules/produce/produceWorkticket";

    }

    /**
     * 拼接一览画面
     *
     * @param values
     * @return
     */
    @RequiresPermissions("produce:workticket:view")
    @RequestMapping(value = {"searchList"})
    @ResponseBody
    public String searchList(ProduceWorkticketEntity produceWorkticketEntity, HttpServletRequest request, HttpServletResponse response,
                             Model model, String[] values) throws Exception {
        Map <Object, Object> listMap = new HashMap <Object, Object> ();
        // ajax回调时使用的一览list名
        request.setAttribute (Global.LIST_NAME, "produceWorkticket");
        // 画面取得的检索项目
        //班组名称
        String groupId = produceWorkticketEntity.getUserGroupEntity().getUserGroupId()+"";
        if ("null".equals(groupId)) {
        	groupId = "";
		}
        //人员姓名
        String personName = produceWorkticketEntity.getPersonName();
        /*//工序名称
        String operatingName = produceWorkticketEntity.getOperatingPEntity().getItemNameCn();*/
        // 开始日期
        String dateStart = produceWorkticketEntity.getDateStart();
        // 截止日期
        String dateEnd = produceWorkticketEntity.getDateEnd();
        // 拼接字符串供分页使用
        String searchParam = "&userGroupEntity.userGroupId=" + groupId + "&personName=" + personName + "&dateStart=" + dateStart + "&dateEnd=" + dateEnd ;
        //放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
        request.setAttribute (Global.SEARCH_PAEAM, searchParam);
        // 查询一览页面数据
        Page <ProduceWorkticketEntity> page = produceWorkticketService.getProduceWorkticketList (new Page <ProduceWorkticketEntity> (request, response),
        		produceWorkticketEntity);
        // 读取文件生成字符串
        String strUri = request.getContextPath () + Global.getAdminPath ();
        String strHtml = "";
        Map <String, Object> map = new HashedMap ();
        map.put ("adminUri", strUri);
        map.put ("workTicketList", page.getList ());
        map.put ("pageNo", page.getPageNo ());
        map.put ("pageSize", page.getPageSize ());
        map.put("springMacroRequestContext", new RequestContext (request));
        strHtml = FreeMarkerTemplateUtils
                .processTemplateIntoString (freemarkerConfiguration.getTemplate ("produceWorkticketList.ftl"), map);
        listMap.put ("produceWorkticket", strHtml);
        listMap.put ("page", page.getHtml ());
        // ajax返回结果
        return renderString (response, listMap);
    }
    
    /**
     * 生产工票一览画面
     *
     * @return
     */
    @RequestMapping(value = {"byOrder"})
    public String produceWorkticketByOrder(Model model) {

        return "modules/produce/produceWorkticketByOrder";

    }
    
    /**
     * 订单检索工票拼接一览画面
     *
     * @param values
     * @return
     */
    @RequiresPermissions("produce:workticket:view")
    @RequestMapping(value = {"searchListByOrder"})
    @ResponseBody
    public String searchListByOrder(ProduceWorkticketEntity produceWorkticketEntity, HttpServletRequest request, HttpServletResponse response,
                             Model model, String[] values) throws Exception {
        Map <Object, Object> listMap = new HashMap <Object, Object> ();
        // ajax回调时使用的一览list名
        request.setAttribute (Global.LIST_NAME, "produceWorkticketByOrder");
        // 画面取得的检索项目
        //订单号
        String orderNo = produceWorkticketEntity.getOrderEntity().getOrderNo();
        // 拼接字符串供分页使用
        String searchParam = "&orderEntity.orderNo=" + orderNo;
        //放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
        request.setAttribute (Global.SEARCH_PAEAM, searchParam);
        // 查询一览页面数据
        Page <ProduceWorkticketEntity> page = produceWorkticketService.getProduceWorkticketListByOrder (new Page <ProduceWorkticketEntity> (request, response),
        		produceWorkticketEntity);
        // 读取文件生成字符串
        String strUri = request.getContextPath () + Global.getAdminPath ();
        String strHtml = "";
        Map <String, Object> map = new HashedMap ();
        map.put ("adminUri", strUri);
        map.put ("produceWorkTicketList", page.getList ());
        map.put ("pageNo", page.getPageNo ());
        map.put ("pageSize", page.getPageSize ());
        map.put("springMacroRequestContext", new RequestContext (request));
        strHtml = FreeMarkerTemplateUtils
                .processTemplateIntoString (freemarkerConfiguration.getTemplate ("produceWorkticketByOrderList.ftl"), map);
        listMap.put ("produceWorkticketByOrder", strHtml);
        listMap.put ("page", page.getHtml ());
        // ajax返回结果
        return renderString (response, listMap);
    }
    /**
     * 导出生产工票
     *
     * @param response
     * @param produceWorkticketEntity
     * @return
     */
    @RequiresPermissions("produce:workticket:view")
    @RequestMapping(value = "exportWorkticket")
    public String exportFile(WorkticketEntity workticketEntity, HttpServletResponse response) {
        try {
            SXSSFWorkbook wb = new SXSSFWorkbook ();
            List<WorkticketEntity> wEntitys = produceWorkticketService.makeOptionList (workticketEntity);
            new ExportExcel ("生产工票", wb, "", WorkticketEntity.class, 2).setDataList (wEntitys);
            sky = wb;
            return renderString (response,"true");
        } catch (Exception e) {
            // 记录日志
            logger.error (e.getMessage (), e);
        }

        // 提示错误信息
        return renderString (response, AjaxDone.error (getText ("System_error_please_contact_your_administrator")));

    }
    /**
     * Excel下载
     *
     * @param response
     * @return
     * @throws Exception
     */
    @RequiresPermissions("produce:workticket:view")
    @RequestMapping(value = {"makeExportFile"})
    public void makeExportFile(WorkticketEntity workticketEntity, HttpServletResponse response, HttpServletRequest request)
            throws Exception {
    	String fileName = DateUtils.getDate("yyyyMMdd") + "生产工票(" + workticketEntity.getDateStart().replace("-", "") + "~" + workticketEntity.getDateEnd().replace("-", "") + ").xlsx";
        response.reset ();
        response.setContentType ("application/octet-stream; charset=utf-8");
        response.setCharacterEncoding ("UTF-8");
        response.setHeader ("Content-Disposition", "attachment; filename=" + new String (fileName.getBytes (), "ISO-8859-1"));
        sky.write (response.getOutputStream ());
    }
    
    /**
     * 查看工票详情
     *
     * @param response
     * @return
     */
    @RequiresPermissions("produce:workticket:view")
    @RequestMapping(value = {"showDetail"})
    public String showDetail(ProduceWorkticketEntity produceWorkticketEntity, HttpServletResponse response, HttpServletRequest request , Model model){
    	try {
    		List<ProduceWorkticketEntity> pEntities =  produceWorkticketService.findDetailList(produceWorkticketEntity);
    		model.addAttribute("workticketDetailList", pEntities);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
    	return "modules/produce/produceWorkticketDetail";
    }
}
